ws-mock
A mock server for websocket testing with the ability to match arbitrarily on received messages and respond accordingly.
WS-Mock allows you to set up a mockserver to test websocket code against, with dynamic responses based on the received data.
Example: Responding to a Heartbeat Message
Using the JsonExact
matcher, WsMock
will match on messages that contain exactly the same json as it was given,
and respond with the string "heartbeat".
Many mocks can be mounted on a single WsMockServer
, and calling server.verify().await
will check that every mock's
expectations were met by incoming messages. Any failures will cause a panic, detailing what messages were seen and
expected.
Either .respond_with(...)
, .forward_from_channel(...)
, or expect(...)
is required for a mock, since mounting a
mock that does not respond, forward messages, or expect any calls will have no discernible effects. This produces a
panic if a WsMock
is mounted without a response or expected number of calls. It's also perfectly valid to .expect(0)
calls to a mock if verifying a certain type of data was never received.
use ;
use json;
use connect_async;
use Message;
use JsonExact;
use ;
pub async
Example: Simulating Live Streaming Data
Many websocket examples don't rely on responding to requests via Websocket, but instead stream data from the server with
no client input. Testing this requires the server accepting messages and sending them to the client.
WsMock.forward_from_channel(...)
accomplishes this by letting the user send arbitrary messages that the server then
relays to the client.
In the below example, the test simulates streaming data by sending messages into the channel configured on the [WsMock].
The mock has no .expect(...)
, or .respond_with(...)
calls, since its only use is forwarding messages that simulate
a live server.
use StreamExt;
use Duration;
use mpsc;
use connect_async;
use Message;
use collect_all_messages;
use ;
pub async
Contributions
Please reach out or submit a PR! Particularly if you have new general purpose Matcher
implementations that would
benefit other users.